package com.kite.videolib.player

import android.content.Context
import android.graphics.SurfaceTexture
import android.net.Uri
import android.util.AttributeSet
import android.view.Surface
import android.view.TextureView
import android.widget.FrameLayout
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import com.kite.videolib.player.databinding.ViewLayoutVideoPlayerBinding


/**
 * Created by YuanWei1 on 2024/11/14.
 *
 * Description:
 */
class VideoPlayMedia3View : FrameLayout, VideoPlayer {
    private var player: ExoPlayer? = null
    val binding by lazy {
        ViewLayoutVideoPlayerBinding.bind(this)
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initMedia()
    }

    private fun initMedia() {
        // 创建ExoPlayer实例
        player = ExoPlayer.Builder(context).build()
        binding.viewVideoPlayerSv.surfaceTextureListener = surfaceTextureListener
    }

    override fun play() {
        player?.play()
    }

    override fun stop() {
    }

    override fun pause() {
        player?.pause()
    }


    override fun setVolume() {

    }

    override fun loadUrl(vararg path: String) {
        val mediaItems = path.map {
            MediaItem.fromUri(Uri.parse(it))
        }
        player?.setMediaItems(mediaItems)
        player?.prepare()
    }

    override fun playSpeed() {
    }

    override fun seekTo() {
    }

    private val surfaceTextureListener: TextureView.SurfaceTextureListener = object : TextureView.SurfaceTextureListener {
        override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
            // 当TextureView的表面纹理可用时，创建Surface并将其与播放器关联
            val surfaceForPlayer = Surface(surface)
            player?.setVideoSurface(surfaceForPlayer)
        }

        override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
            // 处理表面纹理大小变化（如果需要）
        }

        override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
            // 当TextureView的表面纹理被销毁时，释放播放器资源
            player!!.release()
            player = null
            return true
        }

        override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
            // 处理表面纹理更新（通常不需要特别处理）
        }
    }
}